package ru.slovoslovo.cropmotion.cropping;

import java.awt.Dimension;
import java.awt.Rectangle;

public class CropCalculator {

    public static final double PERCENT_PRECISION = 100;

    /**
     * Original image dimensions for crop
     */
    Dimension dimension = null;

    public CropCalculator(Dimension dimension) {
        this.dimension = dimension;
    }

    /**
     * Returns crop rectangle in coordinates of original image
     * 
     * @param cropRegion
     *            crop settings
     * @return crop rectangle
     */
    public Rectangle getCropRectangle(CropRegion cropRegion) {
        Rectangle result = new Rectangle();

        int imageWidth = (int) (dimension.getWidth() * (double) (cropRegion.getCropValue() / PERCENT_PRECISION));
        int imageHeight = (int) (dimension.getHeight() * (double) (cropRegion.getCropValue() / PERCENT_PRECISION));

        int marginHorizontal = (int) (dimension.getWidth() * (double) (cropRegion.getMarginX() / PERCENT_PRECISION));
        int marginVertical = (int) (dimension.getHeight() * (double) (cropRegion.getMarginY() / PERCENT_PRECISION));

        switch (cropRegion.getAlignX()) {
            case LEFT:
                //nothing, marginHorizontal as is
                break;
            case RIGHT:
                marginHorizontal = (int) (getDimension().getWidth() - marginHorizontal - imageWidth);
                break;
            case CENTER:
                //TODO
                break;
        }

        switch (cropRegion.getAlignY()) {
            case TOP:
                //nothing, marginVertical as is
                break;
            case BOTTOM:
                marginVertical = (int) (getDimension().getHeight() - marginVertical - imageHeight);
                break;
            case CENTER:
                //TODO
                break;
        }

        result.setBounds(marginHorizontal, marginVertical, imageWidth, imageHeight);

        return result;
    }

    public Dimension getDimension() {
        return dimension;
    }

    public void setDimension(Dimension dimension) {
        this.dimension = dimension;
    }

}
